package com.itwelkin.ssm.service;

import com.itwelkin.ssm.mapper.CustomerMapper;
import com.itwelkin.ssm.model.Customer;
import com.itwelkin.ssm.model.CustomerCondition;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,readOnly = false)
public class CustomerServicelmpl implements CustomerService{
    private CustomerMapper customerMapper;

    public CustomerServicelmpl(CustomerMapper customerMapper) {
        this.customerMapper = customerMapper;
    }

    @Override
    public List<Customer> queryCustomerList() {
        return customerMapper.queryCustomerList();
    }

    @Override
    public List<Customer> queryCustomerListWithCondtion(String cname, String startAge, String endAge, String clevel) {
        CustomerCondition customerCondition = new CustomerCondition();

        if (cname != null && cname !=""){
            customerCondition.setCname("%" + cname + "%");
        }
        if (startAge != null&& startAge !=""){
            int currentYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()));
            int i =currentYear-Integer.parseInt(startAge);
            startAge = i+"-12-31";
            customerCondition.setStartAge(startAge);
        }
        if (endAge != null&& endAge !=""){
            int currentYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()));
            int i =currentYear-Integer.parseInt(endAge);
            endAge = i+"-1-1";
            customerCondition.setEndAge(endAge);
        }
        if (clevel != null&& clevel !=""){
            customerCondition.setClevel(clevel);
        }
        return customerMapper.queryCustomerListWithCondition(customerCondition);
    }

    @Override
    public void add(Customer customer) {
        customerMapper.add(customer);
    }

    @Override
    public void deleteCustomer(String id) {
        customerMapper.deleteCustomer(id);
    }

    @Override
    public void deleteCustomerWithMore(String[] ids) {
        for (String id : ids) {
            customerMapper.deleteCustomer(id);
        }
    }

    @Override
    public Customer queryCustomerById(String id) {
        return customerMapper.queryCustomerById(id);
    }

    @Override
    public void updateCustomerById(Customer customer) {
        customerMapper.updateCustomerById(customer);
    }
}
